package gw.com.android.ui.quote.view;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.DataManager;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.CommonUtils;
import www.com.library.util.StringUtils;
import www.com.library.view.BtnClickListener;
import www.com.library.view.RecycleViewDivider;


/**
 * 行情底部用户资金栏处理类
 * @author reeta
 *
 */
public class UserInfoHBar extends RelativeLayout {
	@BindView(R.id.user_profit_view)
	RecyclerView mRecyclerView;//左右滑动控件
	@BindView(R.id.user_profit_right)
	ImageView mRightBtn;//右边箭头
	@BindView(R.id.btn_to_deposit)
	TextView mdeposit;//开户按钮
	@BindView(R.id.troust_layout)
	LinearLayout mGuestlayout;//游客登录布局
	@BindView(R.id.change_view)
	AccountChangeView mChangeView;//账号切换按钮

	private AccountChangeViewClickListener mCallback;// 切换按钮点击事件监听器
	private BtnClickListener mBtnClickListener;

	private FragmentActivity mOwnerAct;
	private UserHBarAdapter mAdapter;
	private LinearLayoutManager mLayoutManager;
	private DataItemDetail mUsrInfo;
	private ConfigSettingDeal mSettingDeal;
	private DataItemDetail mDepositDetail;

	public UserInfoHBar(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
		initView(context);
	}

	public UserInfoHBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	public UserInfoHBar(Context context) {
		super(context);
		initView(context);
	}

	public void setBtnClickListener(BtnClickListener mBtnClickListener){
		this.mBtnClickListener =mBtnClickListener;
	}
	/**
	 * 初始化界面控件元素
	 * @param act
	 */
	private void initView(Context act){
		mOwnerAct = (FragmentActivity) act;
		View mView = LayoutInflater.from(act).inflate(R.layout.account_h_info_view, this, true);
		ButterKnife.bind(this, mView);

		mLayoutManager = new LinearLayoutManager(mOwnerAct, LinearLayoutManager.HORIZONTAL, false);
		mRecyclerView.setLayoutManager(mLayoutManager);
		mRecyclerView.addItemDecoration(new RecycleViewDivider(mOwnerAct, LinearLayoutManager.HORIZONTAL));
		mUsrInfo = DataManager.instance().mAccount;
		mAdapter = new UserHBarAdapter();
		mRecyclerView.setAdapter(mAdapter);
		mSettingDeal = new ConfigSettingDeal();
		mDepositDetail = mSettingDeal.getItemValue(ConfigType.DEPOSIT_TAG);
		initData();
	}
	
	/**
	 * 初始化界面数据
	 */
	public void initData(){
		if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
			mdeposit.setText(mOwnerAct.getString(R.string.quote_title_open));
			mRecyclerView.setVisibility(View.GONE);
			mGuestlayout.setVisibility(View.VISIBLE);
			mRightBtn.setVisibility(View.GONE);
		}else if(GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_DEMO){
			mdeposit.setText(mDepositDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
			mRecyclerView.setVisibility(View.VISIBLE);
			mGuestlayout.setVisibility(View.GONE);
			mRightBtn.setVisibility(View.VISIBLE);
		}else{
			mdeposit.setText(mDepositDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
			mRecyclerView.setVisibility(View.VISIBLE);
			mGuestlayout.setVisibility(View.GONE);
			mRightBtn.setVisibility(View.VISIBLE);
		}

		if(null != mChangeView){
			mChangeView.initData();
		}

		updateUserInfo();
	}

	public void refreshView(){
		if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
			mdeposit.setText(mOwnerAct.getString(R.string.quote_title_open));
			mRecyclerView.setVisibility(View.GONE);
			mGuestlayout.setVisibility(View.VISIBLE);
			mRightBtn.setVisibility(View.GONE);
		}else if(GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_DEMO){
			mdeposit.setText(mDepositDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
			mRecyclerView.setVisibility(View.VISIBLE);
			mGuestlayout.setVisibility(View.GONE);
			mRightBtn.setVisibility(View.VISIBLE);
		}else{
			mdeposit.setText(mDepositDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
			mRecyclerView.setVisibility(View.VISIBLE);
			mGuestlayout.setVisibility(View.GONE);
			mRightBtn.setVisibility(View.VISIBLE);
		}

		if(null != mChangeView){
			mChangeView.refreshView();
		}

		updateUserInfo();
	}

	/**
	 * 更新用户资金信息
	 */
	public void updateUserInfo() {
		mUsrInfo = DataManager.instance().mAccount;
		if(null == mUsrInfo){
			return;
		}
		mAdapter.notifyDataSetChanged();
	}

	/**
	 * 游客登录时点击返回登录界面
	 */
	@OnClick(R.id.troust_layout)
	void onGuestClick(){
		if(CommonUtils.isFastDoubleClick()){
			return;
		}
		MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct,"ClickLogin");
		PackStatis.getToService(PackStatis.EventAction.CLICKLOGIN.getValue(),PackStatis.EventCategory.MARKET.getValue(),null,null);
		GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
		ActivityManager.backLogin(mOwnerAct, false);
	}

	/**
	 * 右边箭头，点击滑动资金栏
	 */
	@OnClick(R.id.user_profit_right)
	void onRightArrowClick(){
		if(CommonUtils.isFastDoubleClick()){
			return;
		}
		final int position = mLayoutManager.findLastCompletelyVisibleItemPosition();
		Logger.i("position == " + position);
		mRecyclerView.post(new Runnable() {
			@Override
			public void run() {
				mRecyclerView.smoothScrollToPosition(position + 2);
			}
		});
	}

	/**
	 * 开户
	 */
	@OnClick(R.id.btn_to_deposit)
	void onToDepositClick(){
		if(CommonUtils.isFastDoubleClick()){
			return;
		}
		if(GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL){
			PackStatis.getToService(PackStatis.EventAction.CLICKMONEYSAVE.getValue(),PackStatis.EventCategory.MARKET.getValue(),null,null);
			MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct,"ClickMoneySave");
			ActivityManager.showWebPageActivity(mOwnerAct, mDepositDetail, AppMain.getAppString(R.string.btn_back));
		}else if(GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST){
			PackStatis.getToService(PackStatis.EventAction.CLICKREGBY.getValue(),PackStatis.EventCategory.MARKET.getValue(),null,null);
			MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct,"ClickRegBy");
			ActivityManager.showOpenAccount(mOwnerAct, ConfigType.ADD_LOGIN_REAL_TAG);
		}else{
			MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct,"ClickRegByDemo");
			PackStatis.getToService(PackStatis.EventAction.CLICKREGBYDEMO.getValue(),PackStatis.EventCategory.MARKET.getValue(),null,null);
			mBtnClickListener.onBtnClick(R.id.btn_to_deposit);
		}
	}

	/**
	 * 配置数据
	 * @param idx
	 * @return
	 */
	private String loadData(int idx) {
		if(null == mUsrInfo){
			return null;
		}
		switch (idx) {
			//可用资金(UI端计算  净值-占用保证金)
			case 0:
				if (!DataManager.instance().getLoadDataState(ConfigType.TAB_POSITION_TYPE)) {
					return StringUtils.NA_MSG;
				}
				return mUsrInfo.getString(GTSConst.JSON_KEY_AVAILABLE);
			//净值(UI端计算  净值=余额+总净盈亏)
			case 1:
				if (!DataManager.instance().getLoadDataState(ConfigType.TAB_POSITION_TYPE)) {
					return StringUtils.NA_MSG;
				}
				return mUsrInfo.getString(GTSConst.JSON_KEY_NETWORTH);
			//总净盈亏(UI端计算 当前所有持仓头寸的净盈亏的总和)
			case 2:
				if (!DataManager.instance().getLoadDataState(ConfigType.TAB_POSITION_TYPE))  {
					return StringUtils.NA_MSG;
				}
				return mUsrInfo.getString(GTSConst.JSON_KEY_PROFIT);
			//占用资金(UI端计算 所有持仓头寸所需的保证金之总和)
			case 3:
				if(!DataManager.instance().hasAccount()){
					return StringUtils.NA_MSG;
				}
				return mUsrInfo.getString(GTSConst.JSON_KEY_OCCUPY);
			//余额(服务端传送)
			case 4:
				if(!DataManager.instance().hasAccount()){
					return StringUtils.NA_MSG;
				}
				return mUsrInfo.getString(GTSConst.JSON_KEY_BALANCE);
			//强制平仓点%(服务端传送)
			case 5:
				if(!DataManager.instance().hasAccount()){
					return StringUtils.NA_MSG;
				}
				return mUsrInfo.getString(GTSConst.JSON_KEY_FORCELEVEL);
		}
		return null;
	}

	public class UserHBarAdapter extends RecyclerView.Adapter{

		private LayoutInflater mInflater = null;
		private String[] mProfileTitle;

		public UserHBarAdapter(){
			mInflater = (LayoutInflater) mOwnerAct.getLayoutInflater();
			mProfileTitle = mOwnerAct.getResources().getStringArray(R.array.quote_account_rows);
		}

		@Override
		public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			View itemView = mInflater.inflate(R.layout.list_item_user_info, parent,false);
			return new MenuHolder(itemView);
		}

		@Override
		public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
			final String valueStr = (String) loadData(position);
			MenuHolder holderView = (MenuHolder) holder;
			holderView.mTextV.setText(mProfileTitle[position].replace("：",""));
			if(null != valueStr){
				holderView.mValueV.setText(valueStr);
				if(mProfileTitle[position].equals(AppMain.getAppString(R.string.user_info_profit))){
					if(valueStr.equals("0.00")){
						holderView.mValueV.setTextColor(ColorThemeUtil.instance().color_b);
					}else{
						if(valueStr.contains("-")){
							ColorThemeUtil.instance().setPriceColor(holderView.mValueV, AppContances.PRICE_DECREASE);
						}else{
							ColorThemeUtil.instance().setPriceColor(holderView.mValueV, AppContances.PRICE_INCREASE);
						}
					}
				}else if(mProfileTitle[position].equals(AppMain.getAppString(R.string.user_info_equity))){
					if(null != mUsrInfo && mUsrInfo.getInt(GTSConst.JSON_KEY_NETWORTHSTATE) == AppContances.PRICE_DECREASE){
						holderView.mValueV.setTextColor(ColorThemeUtil.instance().color_red);
					}else{
						holderView.mValueV.setTextColor(ColorThemeUtil.instance().color_b);
					}
				}else{
					holderView.mValueV.setTextColor(ColorThemeUtil.instance().color_b);
				}
			}
		}

		@Override
		public int getItemCount() {
			return mProfileTitle.length;
		}

		/**
		 * item视图控件对象
		 *
		 * @author Administrator
		 *
		 */
		private class MenuHolder extends RecyclerView.ViewHolder{
			public TextView mTextV;
			public TextView mValueV;

			public MenuHolder(View itemView) {
				super(itemView);
				mTextV = (TextView) itemView.findViewById(R.id.item_title);
				mValueV = (TextView) itemView.findViewById(R.id.item_value);
			}
		}
	}

	/**
	 * 设置切换按钮点击监听事件
	 *
	 * @param mCallback
	 */
	public void setAccountChangeViewClickListener(AccountChangeViewClickListener mCallback) {
		this.mCallback = mCallback;
		mChangeView.setAccountChangeViewClickListener(this.mCallback);
	}
	/**
	 * Created by Jay on 2017/6/30.
	 * 自定义控件的按钮点击操作回调
	 */
	public interface AccountChangeViewClickListener {
		/**
		 * 按钮点击监听器回调函数
		 *
		 * @param accountType 切换的账户类型
		 */
		void onViewClick(int accountType);
	}
}
